<template>
  <view class="dispatch-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <text class="nav-back" @click="goBack">返回</text>
      <text class="nav-title">派单管理</text>
      <text class="nav-add" @click="showAddModal">新增派单</text>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-section">
      <view class="stats-card">
        <view class="stats-item">
          <text class="stats-num">{{ stats.totalCount }}</text>
          <text class="stats-label">总派单数</text>
        </view>
        <view class="stats-item">
          <text class="stats-num">{{ stats.pendingCount }}</text>
          <text class="stats-label">待处理</text>
        </view>
        <view class="stats-item">
          <text class="stats-num">{{ stats.completedCount }}</text>
          <text class="stats-label">已完成</text>
        </view>
      </view>
    </view>

    <!-- 筛选条件 -->
    <view class="filter-section">
      <view class="filter-item" @click="showStatusPicker">
        <text class="filter-label">派单状态</text>
        <text class="filter-value">{{ statusText }}</text>
        <text class="filter-arrow">></text>
      </view>
      <view class="filter-item" @click="showTypePicker">
        <text class="filter-label">派单类型</text>
        <text class="filter-value">{{ typeText }}</text>
        <text class="filter-arrow">></text>
      </view>
    </view>

    <!-- 派单列表 -->
    <view class="dispatch-list">
      <view 
        class="dispatch-item" 
        v-for="item in dispatchList" 
        :key="item.id"
        @click="viewDetail(item)"
      >
        <view class="item-header">
          <text class="item-title">{{ item.title }}</text>
          <text class="item-status" :class="getStatusClass(item.status)">
            {{ getStatusText(item.status) }}
          </text>
        </view>
        <view class="item-content">
          <view class="item-row">
            <text class="item-label">派单类型：</text>
            <text class="item-value">{{ item.type }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">派单人员：</text>
            <text class="item-value">{{ item.assignee }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">目标地址：</text>
            <text class="item-value">{{ item.address }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">派单时间：</text>
            <text class="item-value">{{ item.createTime }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">预计完成：</text>
            <text class="item-value">{{ item.expectedTime }}</text>
          </view>
        </view>
        <view class="item-footer">
          <text class="item-priority" :class="getPriorityClass(item.priority)">
            {{ getPriorityText(item.priority) }}
          </text>
          <view class="item-actions" v-if="item.status === 'pending'">
            <text class="action-btn accept" @click.stop="acceptDispatch(item)">接受</text>
            <text class="action-btn reject" @click.stop="rejectDispatch(item)">拒绝</text>
          </view>
          <view class="item-actions" v-else-if="item.status === 'accepted'">
            <text class="action-btn complete" @click.stop="completeDispatch(item)">完成</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="dispatchList.length === 0 && !loading">
      <text class="empty-text">暂无派单信息</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      stats: {
        totalCount: 0,
        pendingCount: 0,
        completedCount: 0
      },
      dispatchList: [],
      loading: false,
      selectedStatus: '',
      selectedType: '',
      pageNum: 1,
      pageSize: 10,
      hasMore: true
    }
  },
  computed: {
    statusText() {
      const statusMap = {
        'pending': '待处理',
        'accepted': '已接受',
        'completed': '已完成',
        'rejected': '已拒绝'
      }
      return statusMap[this.selectedStatus] || '全部状态'
    },
    typeText() {
      const typeMap = {
        'repair': '维修派单',
        'install': '安装派单',
        'inspect': '巡检派单',
        'maintenance': '维护派单'
      }
      return typeMap[this.selectedType] || '全部类型'
    }
  },
  onLoad() {
    this.loadData()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.refreshData()
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    // 显示新增派单弹窗
    showAddModal() {
      uni.navigateTo({
        url: '/pages/dispatch/add'
      })
    },
    
    // 显示状态选择器
    showStatusPicker() {
      uni.showActionSheet({
        itemList: ['全部状态', '待处理', '已接受', '已完成', '已拒绝'],
        success: (res) => {
          const statusMap = ['', 'pending', 'accepted', 'completed', 'rejected']
          this.selectedStatus = statusMap[res.tapIndex]
          this.pageNum = 1
          this.loadData()
        }
      })
    },
    
    // 显示类型选择器
    showTypePicker() {
      uni.showActionSheet({
        itemList: ['全部类型', '维修派单', '安装派单', '巡检派单', '维护派单'],
        success: (res) => {
          const typeMap = ['', 'repair', 'install', 'inspect', 'maintenance']
          this.selectedType = typeMap[res.tapIndex]
          this.pageNum = 1
          this.loadData()
        }
      })
    },
    
    // 加载数据
    async loadData() {
      if (this.loading) return
      
      this.loading = true
      try {
        // 模拟数据
        const mockData = [
          {
            id: 1,
            title: '门禁设备维修',
            type: '维修派单',
            assignee: '张师傅',
            address: '广州市番禺区石壁街大洲村韦大路路心坊自编2号之二',
            status: 'pending',
            priority: 'high',
            createTime: '2024-01-15 14:30:00',
            expectedTime: '2024-01-16 18:00:00'
          },
          {
            id: 2,
            title: '新设备安装',
            type: '安装派单',
            assignee: '李师傅',
            address: '广州市天河区珠江新城',
            status: 'accepted',
            priority: 'medium',
            createTime: '2024-01-14 10:20:00',
            expectedTime: '2024-01-15 17:00:00'
          },
          {
            id: 3,
            title: '设备巡检',
            type: '巡检派单',
            assignee: '王师傅',
            address: '广州市越秀区北京路',
            status: 'completed',
            priority: 'low',
            createTime: '2024-01-13 16:45:00',
            expectedTime: '2024-01-14 12:00:00'
          }
        ]
        
        // 模拟API响应
        const response = {
          code: 200,
          data: {
            rows: mockData,
            total: mockData.length
          }
        }
        
        if (response.code === 200) {
          if (this.pageNum === 1) {
            this.dispatchList = response.data.rows || []
          } else {
            this.dispatchList = [...this.dispatchList, ...(response.data.rows || [])]
          }
          
          this.hasMore = response.data.rows && response.data.rows.length === this.pageSize
          
          // 更新统计数据
          this.updateStats()
        } else {
          this.$modal.msgError(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$modal.msgError('网络异常，请稍后重试')
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },
    
    // 更新统计数据
    updateStats() {
      this.stats.totalCount = this.dispatchList.length
      this.stats.pendingCount = this.dispatchList.filter(item => item.status === 'pending').length
      this.stats.completedCount = this.dispatchList.filter(item => item.status === 'completed').length
    },
    
    // 刷新数据
    refreshData() {
      this.pageNum = 1
      this.loadData()
    },
    
    // 加载更多
    loadMore() {
      this.pageNum++
      this.loadData()
    },
    
    // 查看详情
    viewDetail(item) {
      uni.navigateTo({
        url: `/pages/dispatch/detail?id=${item.id}`
      })
    },
    
    // 接受派单
    acceptDispatch(item) {
      uni.showModal({
        title: '确认操作',
        content: '确定接受此派单吗？',
        success: (res) => {
          if (res.confirm) {
            this.$modal.loading('正在处理...')
            setTimeout(() => {
              this.$modal.closeLoading()
              this.$modal.msgSuccess('操作成功')
              item.status = 'accepted'
              this.updateStats()
            }, 1000)
          }
        }
      })
    },
    
    // 拒绝派单
    rejectDispatch(item) {
      uni.showModal({
        title: '确认操作',
        content: '确定拒绝此派单吗？',
        success: (res) => {
          if (res.confirm) {
            this.$modal.loading('正在处理...')
            setTimeout(() => {
              this.$modal.closeLoading()
              this.$modal.msgSuccess('操作成功')
              item.status = 'rejected'
              this.updateStats()
            }, 1000)
          }
        }
      })
    },
    
    // 完成派单
    completeDispatch(item) {
      uni.showModal({
        title: '确认操作',
        content: '确定完成此派单吗？',
        success: (res) => {
          if (res.confirm) {
            this.$modal.loading('正在处理...')
            setTimeout(() => {
              this.$modal.closeLoading()
              this.$modal.msgSuccess('操作成功')
              item.status = 'completed'
              this.updateStats()
            }, 1000)
          }
        }
      })
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const classMap = {
        'pending': 'status-pending',
        'accepted': 'status-accepted',
        'completed': 'status-completed',
        'rejected': 'status-rejected'
      }
      return classMap[status] || 'status-pending'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        'pending': '待处理',
        'accepted': '已接受',
        'completed': '已完成',
        'rejected': '已拒绝'
      }
      return textMap[status] || '待处理'
    },
    
    // 获取优先级样式
    getPriorityClass(priority) {
      const classMap = {
        'high': 'priority-high',
        'medium': 'priority-medium',
        'low': 'priority-low'
      }
      return classMap[priority] || 'priority-medium'
    },
    
    // 获取优先级文本
    getPriorityText(priority) {
      const textMap = {
        'high': '高优先级',
        'medium': '中优先级',
        'low': '低优先级'
      }
      return textMap[priority] || '中优先级'
    }
  }
}
</script>

<style lang="scss" scoped>
.dispatch-container {
  background-color: #f5f6f7;
  min-height: 100vh;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .nav-back {
    color: #007AFF;
    font-size: 28rpx;
  }
  
  .nav-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .nav-add {
    color: #007AFF;
    font-size: 28rpx;
  }
}

.stats-section {
  padding: 20rpx;
}

.stats-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
  
  .stats-item {
    text-align: center;
    
    .stats-num {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .stats-label {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.filter-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #eee;
  
  .filter-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .filter-label {
      font-size: 28rpx;
      color: #333;
    }
    
    .filter-value {
      font-size: 26rpx;
      color: #666;
      flex: 1;
      text-align: right;
      margin-right: 20rpx;
    }
    
    .filter-arrow {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.dispatch-list {
  padding: 20rpx;
}

.dispatch-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  
  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .item-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
      flex: 1;
    }
    
    .item-status {
      font-size: 24rpx;
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      
      &.status-pending {
        background-color: #fff7e6;
        color: #fa8c16;
      }
      
      &.status-accepted {
        background-color: #e6f7ff;
        color: #1890ff;
      }
      
      &.status-completed {
        background-color: #e8f5e8;
        color: #52c41a;
      }
      
      &.status-rejected {
        background-color: #fff2f0;
        color: #ff4d4f;
      }
    }
  }
  
  .item-content {
    .item-row {
      display: flex;
      margin-bottom: 15rpx;
      
      .item-label {
        font-size: 26rpx;
        color: #666;
        width: 120rpx;
      }
      
      .item-value {
        font-size: 26rpx;
        color: #333;
        flex: 1;
      }
    }
  }
  
  .item-footer {
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .item-priority {
      font-size: 24rpx;
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      
      &.priority-high {
        background-color: #fff2f0;
        color: #ff4d4f;
      }
      
      &.priority-medium {
        background-color: #fff7e6;
        color: #fa8c16;
      }
      
      &.priority-low {
        background-color: #f0f0f0;
        color: #666;
      }
    }
    
    .item-actions {
      display: flex;
      gap: 20rpx;
      
      .action-btn {
        font-size: 24rpx;
        padding: 8rpx 20rpx;
        border-radius: 20rpx;
        
        &.accept {
          background-color: #e8f5e8;
          color: #52c41a;
        }
        
        &.reject {
          background-color: #fff2f0;
          color: #ff4d4f;
        }
        
        &.complete {
          background-color: #e6f7ff;
          color: #1890ff;
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  
  .loading-text {
    font-size: 28rpx;
    color: #666;
  }
}
</style> 